<template>
    <view class="address-edit-page">
        <form :report-submit="true" @submit.prevent="saveAddress">
            <!-- 表单卡片 -->
            <view class="form-card">
                <!-- 收货人信息 -->
                <view class="form-item">
                    <view class="form-label">收货人</view>
                    <input 
                        v-model="formData.name" 
                        placeholder-class="input-placeholder" 
                        class="form-input" 
                        name="name"
                        placeholder="请输入收货人姓名" 
                        maxlength="15" 
                        type="text" 
                    />
                </view>
                
                <view class="divider"></view>
                
                <!-- 手机号码 -->
                <view class="form-item">
                    <view class="form-label">手机号码</view>
                    <input 
                        v-model="formData.mobile" 
                        placeholder-class="input-placeholder" 
                        class="form-input" 
                        name="mobile"
                        placeholder="请输入收货人手机号码" 
                        maxlength="11" 
                        type="text" 
                    />
                </view>
                
                <view class="divider"></view>
                
                <!-- 所在城市 -->
                <picker 
                    :value="value" 
                    mode="multiSelector" 
                    @change="picker" 
                    @columnchange="columnPicker"
                    :range="multiArray" 
                    class="picker-wrapper">
                    <view class="form-item picker-item">
                        <view class="form-label">所在城市</view>
                        <view class="form-input picker-text" :class="{'placeholder': !formData.areaName}">
                            {{formData.areaName || '请选择'}}
                        </view>
                        <tui-icon name="arrowright" color="#ccc" :size="14"></tui-icon>
                    </view>
                </picker>
                
                <view class="divider"></view>
                
                <!-- 详细地址 -->
                <view class="form-item">
                    <view class="form-label">收货地址</view>
                    <input 
                        v-model="formData.detailAddress" 
                        placeholder-class="input-placeholder" 
                        class="form-input"
                        name="address" 
                        placeholder="请输入详细的收货地址" 
                        maxlength="50" 
                        type="text" 
                    />
                </view>
            </view>
            
            <!-- 默认地址开关 -->
            <view class="default-switch-card">
                <view class="switch-item">
                    <view class="switch-label">
                        <text class="switch-title">设为默认地址</text>
                        <text class="switch-desc">保存后该地址将作为默认收货地址</text>
                    </view>
                    <switch 
                        :checked="formData.defaultStatus" 
                        @change="updateDefaultStatus" 
                        color="#E41F19"
                        class="switch-component">
                    </switch>
                </view>
            </view>
            
            <!-- 按钮区域 -->
            <view class="button-area">
                <tui-button 
                    shadow 
                    type="danger" 
                    height="88rpx" 
                    shape="circle"
                    width="100%"
                    @click="validateAndSave"
                    class="save-btn">
                    保存收货地址
                </tui-button>
                <tui-button 
                    v-if="formData.id" 
                    shadow 
                    margin="30rpx 0 0 0" 
                    type="warning" 
                    height="88rpx" 
                    shape="circle"
                    width="100%"
                    @click="confirmDelete"
                    class="delete-btn">
                    删除地址
                </tui-button>
            </view>
        </form>
    </view>
</template>


<script>
    export default {
        data() {
            return {
                ssqList: [],
                multiArray: [],
                value: [0,0,0],
                formData: {
                    id: null,
                    name: "",
                    mobile: "",
                    detailAddress: "",
                    defaultStatus: false,
                    areaName: "",
                    areaId: null
                }
            };
        },
        onLoad(options) {
            if (options.id && options.id !== '0' && options.id !== 0) {
                this.formData.id = parseInt(options.id);
                // 编辑地址，设置标题为"编辑地址"
                uni.setNavigationBarTitle({
                    title: '编辑地址'
                });
            } else {
                // 新增地址，重置表单
                this.formData.id = null;
                this.formData.name = "";
                this.formData.mobile = "";
                this.formData.detailAddress = "";
                this.formData.defaultStatus = false;
                this.formData.areaName = "";
                this.formData.areaId = null;
                // 新增地址，设置标题为"新增地址"
                uni.setNavigationBarTitle({
                    title: '新增地址'
                });
            }
        },
        mounted() {
            // 先加载省市区数据，然后再加载地址信息（如果是编辑模式）
            this.loadSsqList().then(() => {
                if (this.formData.id) {
                    this.loadAddress(this.formData.id);
                }
            });
        },
        methods: {
            // 确认删除
            confirmDelete() {
                uni.showModal({
                    title: "提示",
                    content: "确定要删除该地址吗？",
                    success: (res) => {
                        if (res.confirm) {
                            this.deleteAddress();
                        }
                    },
                });
            },
            // 删除地址
            deleteAddress() {
                if (!this.formData.id || this.formData.id === null || this.formData.id === 0) {
                    return uni.showToast({
                        title: "地址 ID 不存在，无法删除",
                        icon: "none",
                    });
                }

                this.$api.req(`/member/address/delete?id=${this.formData.id}`, {}, "DELETE", "JSON", false).then((res) => {
                    if (res.code === 0) {
                        uni.showToast({
                            title: "删除成功",
                            icon: "success",
                        });
                        setTimeout(() => {
                            uni.navigateBack(); // 删除成功后返回上一页
                        }, 1500);
                    } else {
                        uni.showToast({
                            title: res.msg || "删除失败",
                            icon: "none",
                        });
                    }
                }).catch((err) => {
                    console.error('删除地址失败:', err);
                    uni.showToast({
                        title: "网络错误，请重试",
                        icon: "none",
                    });
                });
            },
            updateDefaultStatus(e) {
                this.formData.defaultStatus = e.detail.value;
            },
            loadAddress(id) {
                this.$api.req(`/member/address/get?id=${id}`, {}, "GET", "JSON", false).then((res) => {
                    if (res.code === 0 && res.data) {
                        const data = res.data;
                        this.formData.id = data.id || null;
                        this.formData.name = data.name || "";
                        this.formData.mobile = data.mobile || "";
                        this.formData.detailAddress = data.detailAddress || "";
                        this.formData.defaultStatus = data.defaultStatus || false;
                        this.formData.areaName = data.areaName || "";
                        this.formData.areaId = data.areaId ? parseInt(data.areaId) : null;

                        // 自动设置 picker 的初始值
                        if (data.areaName && this.ssqList.length > 0) {
                            const areas = data.areaName.trim().split(/\s+/);
                            if (areas.length >= 3) {
                                const pickerValues = this.getPickerValues(areas);
                                if (pickerValues && pickerValues.length === 3) {
                                    this.value = pickerValues;
                                    // 更新 multiArray 以匹配当前选择
                                    const provinceIndex = pickerValues[0];
                                    const cityIndex = pickerValues[1];
                                    if (this.ssqList[provinceIndex] && this.ssqList[provinceIndex].children[cityIndex]) {
                                        this.multiArray[1] = this.toArr(this.ssqList[provinceIndex].children);
                                        this.multiArray[2] = this.toArr(this.ssqList[provinceIndex].children[cityIndex].children);
                                    }
                                }
                            }
                        }
                    } else {
                        uni.showToast({
                            title: res.msg || "加载地址失败",
                            icon: "none"
                        });
                    }
                }).catch((err) => {
                    console.error('加载地址失败:', err);
                    uni.showToast({
                        title: "加载地址失败",
                        icon: "none"
                    });
                });
            },
            getPickerValues(areaNames) {
                let provinceIndex = 0;
                let cityIndex = 0;
                let districtIndex = 0;

                this.ssqList.forEach((province,pIndex) => {
                    if (province.text === areaNames[0]) {
                        provinceIndex = pIndex;
                        province.children.forEach((city,cIndex) => {
                            if (city.text === areaNames[1]) {
                                cityIndex = cIndex;
                                city.children.forEach((district,dIndex) => {
                                    if (district.text === areaNames[2]) {
                                        districtIndex = dIndex;
                                    }
                                });
                            }
                        });
                    }
                });

                return [provinceIndex,cityIndex,districtIndex];
            },
            picker(e) {
                let value = e.detail.value;
                console.log('picker 选择完成:', value);
                
                if (this.ssqList.length > 0 && 
                    value[0] !== undefined && 
                    value[1] !== undefined && 
                    value[2] !== undefined &&
                    this.ssqList[value[0]] &&
                    this.ssqList[value[0]].children &&
                    this.ssqList[value[0]].children[value[1]] &&
                    this.ssqList[value[0]].children[value[1]].children &&
                    this.ssqList[value[0]].children[value[1]].children[value[2]]) {
                    
                    let province = this.ssqList[value[0]].text;
                    let city = this.ssqList[value[0]].children[value[1]].text;
                    let district = this.ssqList[value[0]].children[value[1]].children[value[2]].text;
                    this.formData.areaName = province + " " + city + " " + district;
                    this.formData.areaId = parseInt(this.ssqList[value[0]].children[value[1]].children[value[2]].value);
                    this.value = value;
                    console.log('选择完成，区域名称:', this.formData.areaName, '区域ID:', this.formData.areaId);
                } else {
                    console.error('picker 数据异常:', value, this.ssqList);
                }
            },
            columnPicker(e) {
                // 多列选择器的列变化处理
                const column = e.detail.column;
                const row = e.detail.value;
                
                console.log('columnPicker 被调用:', column, row, this.ssqList.length);
                
                if (column === 0) {
                    // 第一列（省）变化，更新第二列（市）和第三列（区）
                    if (this.ssqList[row] && this.ssqList[row].children) {
                        const cities = this.toArr(this.ssqList[row].children);
                        let districts = [];
                        if (this.ssqList[row].children && this.ssqList[row].children.length > 0 && this.ssqList[row].children[0].children) {
                            districts = this.toArr(this.ssqList[row].children[0].children);
                        }
                        // 使用 Vue.set 或重新赋值整个数组来触发响应式更新
                        this.$set(this.multiArray, 1, cities);
                        this.$set(this.multiArray, 2, districts);
                        this.value = [row, 0, 0];
                    }
                } else if (column === 1) {
                    // 第二列（市）变化，更新第三列（区）
                    const provinceIndex = this.value[0];
                    if (this.ssqList[provinceIndex] && this.ssqList[provinceIndex].children && this.ssqList[provinceIndex].children[row]) {
                        const districts = this.ssqList[provinceIndex].children[row].children 
                            ? this.toArr(this.ssqList[provinceIndex].children[row].children)
                            : [];
                        this.$set(this.multiArray, 2, districts);
                        this.value = [provinceIndex, row, 0];
                    }
                } else if (column === 2) {
                    // 第三列（区）变化，只更新值
                    this.value = [this.value[0], this.value[1], row];
                }
            },
            loadSsqList() {
                return this.$api.req("/system/area/tree", {}, "GET", "JSON", false).then((res) => {
                    if (res.code === 0) {
                        console.log('API 返回的原始数据:', res.data);
                        this.ssqList = this.transformData(res.data);
                        console.log('转换后的数据:', this.ssqList);
                        
                        if (this.ssqList.length > 0) {
                            const provinces = this.toArr(this.ssqList);
                            const cities = this.ssqList[0].children && this.ssqList[0].children.length > 0 
                                ? this.toArr(this.ssqList[0].children) 
                                : [];
                            const districts = this.ssqList[0].children && this.ssqList[0].children[0] && this.ssqList[0].children[0].children
                                ? this.toArr(this.ssqList[0].children[0].children)
                                : [];
                            
                            this.multiArray = [provinces, cities, districts];
                            console.log('multiArray 初始化:', this.multiArray);
                        }
                    }
                }).catch((err) => {
                    console.error('加载省市区数据失败:', err);
                    uni.showToast({
                        title: "加载省市区数据失败",
                        icon: "none"
                    });
                });
            },
            toArr(object) {
                if (!object || !Array.isArray(object)) {
                    return [];
                }
                // 如果对象是数组，直接返回文本数组
                return object.map(item => item.text || item.name || String(item));
            },
            transformData(data) {
                return data.map(item => ({
                    text: item.name,
                    value: String(item.id),
                    children: item.children.map(subItem => ({
                        text: subItem.name,
                        value: String(subItem.id),
                        children: subItem.children.map(child => ({
                            text: child.name,
                            value: String(child.id)
                        }))
                    }))
                }));
            },
            validateAndSave() {
                if (!this.formData.name.trim()) {
                    return uni.showToast({ title: "请输入收货人姓名",icon: "none" });
                }
                if (this.formData.name.length > 10) {
                    return uni.showToast({ title: "收货人姓名不能超过10个字符",icon: "none" });
                }
                if (!this.formData.mobile.trim()) {
                    return uni.showToast({ title: "请输入手机号码",icon: "none" });
                }
                const mobileRegex = /^1[3-9]\d{9}$/; // 手机号正则
                if (!mobileRegex.test(this.formData.mobile)) {
                    return uni.showToast({ title: "请输入正确的手机号码",icon: "none" });
                }
                if (!this.formData.areaName.trim()) {
                    return uni.showToast({ title: "请选择所在城市",icon: "none" });
                }
                if (!this.formData.detailAddress.trim()) {
                    return uni.showToast({ title: "请输入详细地址",icon: "none" });
                }
                this.saveAddress();
            },
            saveAddress() {
                // 判断是新增还是更新
                const isUpdate = this.formData.id !== null && this.formData.id !== undefined && this.formData.id !== 0;
                const url = isUpdate ? `/member/address/update` : `/member/address/create`;
                const method = isUpdate ? "PUT" : "POST";

                // 准备发送的数据
                const dataToSend = {
                    name: this.formData.name.trim(),
                    mobile: this.formData.mobile.trim(),
                    detailAddress: this.formData.detailAddress.trim(),
                    defaultStatus: this.formData.defaultStatus,
                    areaName: this.formData.areaName.trim(),
                    areaId: this.formData.areaId ? parseInt(this.formData.areaId) : null
                };

                // 如果是更新，添加 id
                if (isUpdate) {
                    dataToSend.id = parseInt(this.formData.id);
                }

                console.log('保存地址数据:', dataToSend);

                this.$api.req(url, dataToSend, method, "JSON", false).then((res) => {
                    if (res.code === 0) {
                        uni.showToast({
                            title: isUpdate ? "更新成功" : "保存成功",
                            icon: "success"
                        });
                        setTimeout(() => {
                            uni.navigateBack(); // 保存或更新成功后返回上一页
                        }, 1500);
                    } else {
                        uni.showToast({
                            title: res.msg || "操作失败",
                            icon: "none"
                        });
                    }
                }).catch((err) => {
                    console.error('保存地址失败:', err);
                    uni.showToast({
                        title: "网络错误，请重试",
                        icon: "none"
                    });
                });
            }

        }
    };
</script>


<style>
    .address-edit-page {
        min-height: 100vh;
        background: #f5f5f5;
        padding-bottom: 40rpx;
    }

    /* 表单卡片 */
    .form-card {
        background: #fff;
        border-radius: 20rpx;
        margin: 20rpx 30rpx;
        overflow: hidden;
        box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
    }

    .form-item {
        display: flex;
        align-items: center;
        padding: 32rpx 30rpx;
        min-height: 100rpx;
        box-sizing: border-box;
    }

    .form-label {
        width: 180rpx;
        font-size: 30rpx;
        color: #333;
        font-weight: 500;
        flex-shrink: 0;
    }

    .form-input {
        flex: 1;
        font-size: 30rpx;
        color: #333;
        text-align: right;
    }

    .input-placeholder {
        color: #999;
        font-size: 30rpx;
    }

    .divider {
        height: 1rpx;
        background: #f0f0f0;
        margin-left: 30rpx;
    }

    /* 选择器样式 */
    .picker-wrapper {
        width: 100%;
        display: block;
    }

    .picker-item {
        cursor: pointer;
    }

    .picker-text {
        text-align: right;
        color: #333;
    }

    .picker-text.placeholder {
        color: #999;
    }

    /* 默认地址开关卡片 */
    .default-switch-card {
        background: #fff;
        border-radius: 20rpx;
        margin: 20rpx 30rpx;
        padding: 30rpx;
        box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
    }

    .switch-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .switch-label {
        display: flex;
        flex-direction: column;
        gap: 8rpx;
        flex: 1;
    }

    .switch-title {
        font-size: 30rpx;
        color: #333;
        font-weight: 500;
    }

    .switch-desc {
        font-size: 24rpx;
        color: #999;
    }

    .switch-component {
        transform: scale(1.1);
    }

    /* 按钮区域 */
    .button-area {
        padding: 40rpx 30rpx;
        padding-bottom: calc(40rpx + env(safe-area-inset-bottom));
    }

    .save-btn {
        width: 100%;
    }

    .delete-btn {
        width: 100%;
    }
</style>